/**************************************************
 * Project Name         [JavaEE_XML]
 * File Name            [JDOMCRUD.java]
 * Creation Date        [08-21-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 **************************************************/
package pkg_04_jdom;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/**
 * JDOM 节点元素增删改查
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class JDOMCRUD {

	/**
	 * 测试方法
	 * 
	 * @param args
	 * @throws IOException
	 * @throws JDOMException
	 */
	public static void main(String[] args) throws JDOMException, IOException {
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(new File(
				"src/xml/Student_JDOM.xml"));

		// 增加元素, 如果有多个元素则只添加到第一个Student
		Element newElement = new Element("Hobby");
		newElement.setText("Music");
		document.getRootElement().getChild("Student").addContent(newElement);

		// 修改元素, 如果有多个元素则只修改第一个Student的Name
		document.getRootElement().getChild("Student").getChild("Name")
				.setText("CC");

		// 删除元素, 如果有多个元素则至删除第一个Student的Age
		document.getRootElement().getChild("Student").removeChild("Age");

		XMLOutputter out = new XMLOutputter();
		Format format = Format.getPrettyFormat();
		format.setEncoding("UTF-8");
		format.setIndent("    ");// 设置缩进
		out.setFormat(format);
		out.output(document, new FileOutputStream(new File(
				"src/xml/Student_JDOM.xml")));

	}

}
